import sys
import execute,jieba
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import *

# 表示从PyQt5的QtWidgets中引用全部函数（*表示全部）
word_flag = 0
bg_flag = 0


# 继承
class ChatBox(QWidget):
    def __init__(self):
        # 初始化父类构造函数
        # super会找到ChatBox继承的父类QWindegt， 去实例化父类的构造函数
        super(ChatBox, self).__init__()
        # 绘制界面方法
        # 初始化界面
        self.initUI()

    def AI_robot(self,sentence):
        new = " ".join(jieba.cut(sentence))
        sentence = execute.predict(new)
        sentence = sentence.replace('_UNK', '^_^')
        sentence = sentence.replace('start', '')
        sentence = sentence.replace('end', '')
        sentence = sentence.replace('<EOS>', '')
        sentence = sentence.replace(' ', '')
        sentence = sentence.strip()
        # 如果接受到的内容为空，则给出相应的回复
        if sentence == ' ':
            sentence = '请与我聊聊天吧QAQ'
        return sentence

    def initUI(self):
        self.setWindowTitle("聊天机器人")
        self.setGeometry(500, 100, 800, 700)
        # 美化窗口+添加控件
        # 窗口图标
        self.icon = QtGui.QIcon()
        self.icon.addPixmap(QtGui.QPixmap("jiqiren2.png"),    # 图标路径
                            QtGui.QIcon.Normal,
                            QtGui.QIcon.Off)
        self.setWindowIcon(self.icon)
        # 左侧栏
        self.left_box = QWidget(self)
        self.left_box.setGeometry(10, 10, 200, 680)
        self.left_box.setStyleSheet("background-image: url(zuoxiabeijingtu.png)")  # 设置背景

        #
        self.AI = QLabel("\n\n\n 聊天机器人小帅在线中", self)
        self.AI.setGeometry(10, 10, 200, 120)
        self.AI.setStyleSheet(" background-image: url(jiqiren2.png);color: orange; font-size:18px")

        # 右上方聊天区
        self.chatBox = QListWidget(self)
        # 设置位置
        self.chatBox.setGeometry(210, 10, 590, 600)
        # 设置图标大小
        self.chatBox.setIconSize(QSize(40, 40))

        # 右下方内容准备
        self.char_input = QLineEdit(self)
        self.char_input.setGeometry(210, 615, 480, 80)
        self.char_input.setStyleSheet("color:black; font-size:30px; border: 10px solid #f4f4f4; "
                                      "background-color: rgb(255, 255, 255);")
        # 发送按钮
        self.submit = QPushButton('发送', self)
        self.submit.setToolTip('点击发送')  # 当鼠标放上去后显示的内容
        self.submit.setGeometry(695, 615, 100, 80)
        self.submit.setStyleSheet("color:black; font-size:20px; font-weight:bold; border-radius:2;"
                                  "background-color: rgb(131, 175, 155);")
        # 点击发送按钮，发送消息
        item = QListWidgetItem(QIcon("jiqiren.png"), "你好！有什么可以为你分忧的？", self.chatBox)
        self.submit.clicked.connect(self.send_message)
        self.submit.setShortcut('enter')

    def send_message(self):
        # 用户输出什么信息
        content = self.char_input.text()
        if len(content) == 0:
            return     # 函数终结
        # 把输入的信息显示在聊天区
        item = QListWidgetItem(QIcon("yonghu.png"), content, self.chatBox)
        # 清空输入框
        self.char_input.clear()
        robot_reply = self.AI_robot(content)
        self.deal_message(content)
        # 下面这个是处理重复输入
        robot_reply = self.deal_reprtion(robot_reply)
        self.reply(robot_reply)

    # 消息回复
    def reply(self, robot_reply):
        if robot_reply is None:
            return
        if len(robot_reply) >= 40:
            count = int(len(robot_reply)/40)
            for i in range(0, count):
                if i ==0:
                    res = robot_reply[40*i:(40*(i+1)-1)]
                    item = QListWidgetItem(QIcon("jiqiren.png"), res, self.chatBox)
                else:
                    res = robot_reply[40*i-1:(40 * (i+1)-1)]
                    item = QListWidgetItem(res, self.chatBox)
            if len(robot_reply)/40 > count:
                res = robot_reply[40*count-1:]
                item = QListWidgetItem(res, self.chatBox)
            return
        item = QListWidgetItem(QIcon("jiqiren.png"), robot_reply, self.chatBox)

    def deal_message(self,content):
        # 处理重复输入
        global word_flag, connect_word
        if word_flag == 0:
            connect_word = content
        if connect_word == content:
            word_flag = word_flag + 1
        else:
            word_flag = 0

    def deal_reprtion(self, robot_reply):
        global word_flag
        if word_flag == 2:
            robot_reply = '我不理解你的意思，换个话题'
        elif word_flag == 3:
            robot_reply = '你是憨憨嘛？都说了不懂你还问，再问就不理你了。'
        elif word_flag == 4:
            robot_reply = '哼，不理你了'
        elif word_flag >= 5:
            robot_reply = None
        return robot_reply



# 控件  位置  样式
# 程序的主入口会有main函数
# python把每一个py脚本看成模块，可以单独运行
if __name__ == "__main__":
    # 实例化一个应用对象
    app = QtWidgets.QApplication(sys.argv)
    # 实例化聊天窗
    win = ChatBox()
    win.show()
    sys.exit(app.exec_())
